/*
 * 课时Lesson基本信息编辑
 */
import * as React from 'react';
import { connect } from 'react-redux';
import { Input, Button, message, Form } from 'antd';
import { get } from 'lodash';

import { createLesson, updateLesson } from 'actions/lesson';
import { isLoading } from 'utils/utils';
import ACTIONS from 'constants/lesson';

interface BasicEditProps {
  dispatch: (action: any) => any;
  handleCallback: (id: number) => void;
  form: any;
  lessonDetail: any;
  courseId: number;
  loadingGroup: any;
}

class EditBasic extends React.Component<BasicEditProps> {
  loadingKey: string;
  static defaultProps: BasicEditProps = {
    dispatch: () => {},
    handleCallback: () => {},
    form: {},
    courseId: 0,
    lessonDetail: null,
    loadingGroup: {},
  };
  constructor(props: BasicEditProps) {
    super(props);

    this.loadingKey = props.lessonDetail ? ACTIONS.UPDATE : ACTIONS.CREATE;
  }

  initFormValues(lessonDetail: any) {
    const { form } = this.props;

    const name = get(lessonDetail, 'name', '');
    const description = get(lessonDetail, 'description', '');
    const lexile = get(lessonDetail, 'lexile', '');

    // 不能设置不在render getFieldDecorator注册的项
    form.setFieldsValue({
      name,
      description,
      lexile,
    });
  }

  componentDidMount() {
    this.initFormValues(this.props.lessonDetail);
  }

  componentWillReceiveProps(nextProps: any) {
    const lessonId = get(nextProps, 'lessonDetail.id', 0);
    const oldLessonId = get(this.props, 'lessonDetail.id', 0);
    if (lessonId !== oldLessonId) {
      this.initFormValues(nextProps.lessonDetail);
    }
  }

  handleSubmit = (e: any) => {
    e.preventDefault();

    const { form, dispatch, loadingGroup, courseId, lessonDetail, handleCallback } = this.props;

    if (isLoading(loadingGroup, this.loadingKey)) return;

    form.validateFields((error: any, values: any) => {
      if (error) return;

      let data: any = {};
      Object.keys(values).map((key: any) => {
        const val = values[key];
        if (val) {
          data[key] = val;
        }
      });

      const action = lessonDetail
        ? updateLesson(courseId, lessonDetail.id, data)
        : createLesson(courseId, data);

      dispatch(action).then((result: any) => {
        if (result.code) {
          message.error(result.msg);
        } else {
          message.success('保存成功');

          const id = lessonDetail ? lessonDetail.id : result.response.data.id;
          handleCallback(id);
        }
      });
    });
  };

  render() {
    const { getFieldDecorator } = this.props.form;
    const { loadingGroup } = this.props;

    return (
      <Form onSubmit={this.handleSubmit}>
        <Form.Item label="Lesson名称">
          {getFieldDecorator('name', {
            rules: [
              {
                required: true,
                message: 'Lesson名称是必填项',
              },
            ],
          })(<Input placeholder="填写Lesson名称" />)}
        </Form.Item>
        <Form.Item label="Lesson描述">
          {getFieldDecorator('description')(
            <Input.TextArea
              placeholder="填写Lesson描述"
              autosize={{
                minRows: 2,
                maxRows: 6,
              }}
            />
          )}
        </Form.Item>
        <Form.Item label="CEFR指标">
          {getFieldDecorator('lexile', {})(<Input placeholder="填写CEFR指标" />)}
        </Form.Item>
        <Form.Item>
          <Button.Group>
            <Button
              type="primary"
              htmlType="submit"
              loading={isLoading(loadingGroup, this.loadingKey)}>
              &nbsp;&nbsp;&nbsp;保存&nbsp;&nbsp;&nbsp;
            </Button>
            &nbsp;&nbsp;&nbsp;
          </Button.Group>
        </Form.Item>
      </Form>
    );
  }
}

interface OwnProps {
  courseId: number;
  lessonDetail: any;
  handleCallback: (id: number) => any;
}

function mapStateToProps(state: any, ownProps: OwnProps) {
  const { courseId, lessonDetail } = ownProps;
  const { loadingGroup } = state;

  return {
    loadingGroup,
    lessonDetail,
    courseId,
  };
}

export default connect(mapStateToProps)(Form.create()(EditBasic));
